import Vue from 'vue'
import config from '@/config/app.config.js'
// import news from '@/service/service/news.service.js'
// import service from '@/service/service/service.service.js'
import * as system from '@/api/system.js'
import * as news from '@/api/news.js'
import * as service from '@/api/service.js'
import * as category from '@/api/category.js'
import * as map from '@/api/map.js'

export default (context) => {
  const $service = {
    config,
    getters: {
      resolveSrc, getImageSrc, getSourceSrc
    },
    system, news, service, category, map
  }
  // 添加全局方法或属性
  context.$service = $service
  Vue.prototype.$service = $service
}

// 全局资源地址
const getSourceSrc = function (url, setting) {
  if (/,/.test(url)) {
    url = url.split(',')[0]
  }
  if (/(https?:)?\/\//.test(url)) {
    return url
  }
  setting = setting || config
  let basePATH = setting.basePATH
  if (url) {
    if (url.indexOf(basePATH) === 0) {
      url = url.replace(basePATH, setting.baseURL)
    } else {
      url = setting.baseURL + ('/' + url).replace(/^\/+/, '/')
    }
  }
  return url
}
Vue.prototype.getSourceSrc = getSourceSrc

// 全局获取图片地址
const getImageSrc = function (url) {
  if (!url) {
    return '/assets/images/news-default.jpg'
  }
  if (/,/.test(url)) {
    url = url.split(',')[0]
  }
  if (/(https?:)?\/\//.test(url)) {
    return url
  }
  url = getSourceSrc(url)
  return url
}
Vue.prototype.getImageSrc = getImageSrc

// 解析资源地址
const resolveSrc = function (text) {
  text = String(text)
  text = text.replace(/((src|href)=")([^"]+)/g, function(a, b, c, d){
    return b + getSourceSrc(d)
  })
  return text
}
Vue.prototype.resolveSrc = resolveSrc